package top.eggcode.template.dict;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import top.eggcode.component.dict.DictSource;
import top.eggcode.system.client.DictClientService;
import top.eggcode.system.client.model.Word;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Title:
 * Description: TODO
 * Date: 2021/6/24 12:56
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Component
@RequiredArgsConstructor
public class SystemDictStore implements DictSource {

    private final DictClientService dictClientService;
    private Map<String, Map<String, String>> cacheBox = new HashMap<>();

    @Override
    public Map<String, String> getDict(String code) {
        List<Word> dictData = dictClientService.getWords(code).getData();
        Map<String, String> dictMap = new HashMap<>(10);
        dictData.forEach(word -> {
            dictMap.put(word.getValue(), word.getName());
        });
        cacheBox.put(code, dictMap);
        return dictMap;
    }

    @Override
    public String getWord(String dict, String word) {
        Map<String, String> cacheVal = cacheBox.get(dict);
        if (cacheVal != null) {
            return cacheVal.get(word);
        } else {
            Map<String, String> dictMap = getDict(dict);
            cacheBox.put(dict, dictMap);
            return dictMap.get(word);

        }

    }
}
